//更新用户头像
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database() //数据库
const updateAvatar = async function (params) {
  //更新用户的头像
  const wxContext = cloud.getWXContext()
  const cloudPath = "user/avatar_" + wxContext.OPENID + params.cloudPath
  const fileResult = await cloud.uploadFile({
    cloudPath: cloudPath,
    fileContent: Buffer.from(params.filePath)
  })
  //获取真实的Url
  const fileList = [fileResult.fileID]
  const UrlResult = await cloud.getTempFileURL({
    fileList: fileList,
  })
  const img = UrlResult.fileList[0].tempFileURL+"?t="+Date.parse(new Date())
  const updateResults = await db.collection('user').where({
    _openid: wxContext.OPENID
  }).update({
    data: {
      headPortrait: img
    }
  })
  if (updateResults.stats) {
    return {
      cloudPath: img
    }
  }
}
module.exports = updateAvatar